<template>
  <div v-loading="loading">
    <div v-if="+relatedData.confuse_status === 3" class="empty-wrap text-left">
      <ul class="list-group">
        <li class="list-group-item">项目名称： {{ relatedData.customer_name }}</li>
        <li class="list-group-item">
          项目状态：
          <span class="text-danger">已拒绝</span>
        </li>
        <li class="list-group-item">拒绝时间： {{ relatedData.confuse_time }}</li>
        <!-- <li class="list-group-item">拒绝人：{{ relatedData.item_person_name }}</li> -->
        <li class="list-group-item">拒绝理由：{{ relatedData.confuse_des }}</li>
      </ul>
    </div>
    <div v-else>
      <table class="table table-bordered vertical-align-middle text-center">
        <colgroup>
          <col width="14%" />
          <col width="20%" />
          <col width="14%" />
          <col width="19%" />
          <col width="14%" />
          <col width="19%" />
        </colgroup>
        <tbody>
          <tr>
            <td>主体姓名</td>
            <td colspan="5" class="text-left">{{ relatedData.customer_name || '' }}</td>
          </tr>
          <tr>
            <td>
              <span class="text-danger">*</span>
              放款金额
            </td>
            <td :class="tdClass">
              <span v-if="isViewMode">{{ relatedData.reply_funds }} 万元</span>
              <el-input
                v-else
                placeholder="放款金额"
                clearable
                v-input-number="{ min: 0 }"
                v-model="editData.reply_funds"
                @change="setGuaFee"
              >
                <span slot="append">万元</span>
              </el-input>
            </td>
            <td>
              <span class="text-danger">*</span>
              贷款期限
            </td>
            <td :class="tdClass">
              <span v-if="isViewMode">{{ relatedData.months }} 月</span>
              <el-input
                v-else
                placeholder="贷款期限"
                clearable
                v-input-number="{ min: 0, fixed: 2 }"
                v-model="editData.months"
                @change="setGuaFee"
              >
                <span slot="append">月</span>
              </el-input>
            </td>
            <td>
              <!-- <span class="text-danger">*</span> -->
              担保费率
            </td>
            <td :class="tdClass">
              <span v-if="isViewMode">
                {{ +relatedData.gua_rate || entrustContract.gua_rate || '-' }}%
              </span>
              <el-input
                v-else
                v-model="editData.gua_rate"
                placeholder="担保费率"
                v-input-number="{ fixed: 4 }"
                @change="setGuaFee"
              >
                <span slot="append">%</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td class="td-label">
              <span class="text-danger">*</span>
              保费收取方式
            </td>
            <td :class="tdClass" colspan="5">
              <span v-if="isViewMode">
                {{ enumGuaFundsSelfType[editData.gua_fee_coll_type] }}
              </span>
              <div style="padding: 0.6rem; background-color: #ffffee" v-else>
                <c-radio-group
                  v-model="editData.gua_fee_coll_type"
                  :options="enumGuaFundsSelfType"
                  @change="setGuaFee"
                ></c-radio-group>
              </div>
            </td>
          </tr>
          <tr>
            <td class="td-label">
              <!-- <span class="text-danger">*</span> -->
              担保费
            </td>
            <td :class="tdClass" colspan="5" class="p-0">
              <table class="table table-sm table-borderless bg-white table-vertical-middle m-0">
                <colgroup>
                  <col width="33%" />
                  <col width="33%" />
                  <col width="33%" />
                </colgroup>
                <tr class="text-muted">
                  <td class="border-right">预计缴费时间</td>
                  <td class="border-right">计划在保余额</td>
                  <td>缴费金额</td>
                </tr>
                <template v-for="(item, index) of guaFeeData">
                  <tr :key="index">
                    <td :class="tdClass" class="border-top border-right">
                      <span v-if="isViewMode">
                        {{ $utils.dateFormat(item.due_warrant_date, 'yyyy-MM-dd') }}
                      </span>
                      <el-date-picker
                        v-else
                        class="w-100"
                        v-model="item.due_warrant_date"
                        @change="setDueDate(item.due_warrant_date, index)"
                        placeholder="缴费时间"
                        type="date"
                        value-format="yyyy-MM-dd"
                      ></el-date-picker>
                    </td>
                    <td :class="tdClass" class="border-top border-right">
                      <span v-if="isViewMode">{{ item.plan_left_funds }} 万元</span>
                      <el-input
                        v-else
                        v-input-number="{ min: 0 }"
                        placeholder="计划在保余额"
                        :disabled="+editData.gua_fee_coll_type === 1"
                        v-model="item.plan_left_funds"
                        @change="setItemFee(item.plan_left_funds, item)"
                      >
                        <span slot="append">万元</span>
                      </el-input>
                    </td>
                    <td :class="tdClass" class="border-top">
                      <span v-if="isViewMode">{{ item.actual_warrant_fee }} 万元</span>
                      <el-input
                        v-else
                        v-input-number="{ min: 0 }"
                        placeholder="缴费金额"
                        :disabled="+editData.gua_fee_coll_type === 1"
                        v-model="item.actual_warrant_fee"
                      >
                        <span slot="append">万元</span>
                      </el-input>
                    </td>
                  </tr>
                </template>
              </table>
            </td>
          </tr>
          <tr>
            <td>
              <span class="text-danger">*</span>
              贷款利率(%)
            </td>
            <td :class="tdClass">
              <span v-if="isViewMode">
                {{ relatedData.load_rate || entrustContract.load_rate || '-' }}%
              </span>
              <el-input
                v-else
                v-model="editData.load_rate"
                placeholder="贷款利率"
                v-input-number="{ fixed: 4 }"
              >
                <span slot="append">%</span>
              </el-input>
            </td>
            <td>
              <span class="text-danger">*</span>
              放款时间
            </td>
            <td :class="tdClass">
              <span class="px-2" v-if="isViewMode">
                {{ $utils.dateFormat(relatedData.load_date, 'yyyy年MM月dd日') }}
              </span>
              <el-date-picker
                v-else
                v-model="editData.load_date"
                :clearable="false"
                type="date"
                placeholder="放款开始时间"
                class="w-100"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </td>
            <td>
              <span class="text-danger">*</span>
              到期时间
            </td>
            <td :class="tdClass">
              <span class="px-2" v-if="isViewMode">
                {{ $utils.dateFormat(relatedData.load_end_date, 'yyyy年MM月dd日') }}
              </span>
              <el-date-picker
                v-else
                v-model="editData.load_end_date"
                :clearable="false"
                type="date"
                placeholder="放款结束时间"
                class="w-100"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </td>
          </tr>

          <tr>
            <td>
              <span class="text-danger">*</span>
              放款银行名称
            </td>
            <td colspan="5" class="text-left" :class="tdClass">
              <span v-if="isViewMode">{{ relatedData.bank_name }}</span>
              <select-org-bank
                v-else
                v-model="editData.bank_id"
                :project-type="relatedData.gua_type"
                placeholder="选择最终放款银行（用于项目统计，可输入模糊查询）"
                @select="setPublicName"
                filterable
                class="w-100"
              ></select-org-bank>
            </td>
          </tr>
          <tr>
            <td>
              <span class="text-danger">*</span>
              还款计划
            </td>
            <td colspan="5" class="p-0">
              <table class="table table-sm table-borderless bg-white table-vertical-middle m-0">
                <colgroup>
                  <col width="50%" />
                  <col width="50%" />
                </colgroup>
                <tr class="text-muted">
                  <td class="border-right">还款时间</td>
                  <td>应还本金(元)</td>
                </tr>
                <tr v-if="!playList.length">
                  <td colspan="2" class="text-muted text-small border-top">暂无数据</td>
                </tr>
                <template v-for="(item, index) of playList">
                  <tr
                    :key="index"
                    :class="{ 'tr-current': playIndex === index }"
                    @click="handleRowClick(index)"
                  >
                    <td :class="tdClass" class="border-top border-right">
                      <span v-if="isViewMode">
                        {{ $utils.dateFormat(item.pay_time, 'yyyy-MM-dd') }}
                      </span>
                      <el-date-picker
                        v-else
                        class="w-100"
                        v-model="item.pay_time"
                        placeholder="还款时间"
                        type="date"
                        value-format="yyyy-MM-dd"
                      ></el-date-picker>
                    </td>
                    <td :class="tdClass" class="border-top">
                      <span v-if="isViewMode">{{ item.capital }}</span>
                      <el-input
                        v-else
                        v-input-number="{ min: 0, fixed: 2 }"
                        placeholder="应还本金"
                        v-model="item.capital"
                      >
                        <span slot="append">元</span>
                      </el-input>
                    </td>
                  </tr>
                </template>
                <tr>
                  <td class="border-top border-right">合计</td>
                  <td class="border-top border-right">{{ repaySum }}</td>
                </tr>
                <tr class="text-left">
                  <td colspan="2" class="border-top border-right p-1">
                    <div class="mt-1">
                      <el-button-group class="mb-2" v-if="!isViewMode">
                        <el-button size="small" @click="handleRowAdd">
                          <i class="fa fa-indent"></i>
                          添加一行
                        </el-button>

                        <el-button size="small" @click="handleRowDelete">
                          <i class="fa fa-outdent"></i>
                          删除当前行
                        </el-button>
                      </el-button-group>
                    </div>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          <tr>
            <td>{{ attachTag }}</td>
            <td colspan="5" class="text-left">
              <div v-if="isViewMode">
                <div class="empty-wrap" v-if="!attachList.length">暂无附件（借据）</div>
                <attach-list v-else :attath-data="viewList" :show-label="false"></attach-list>
              </div>
              <upload-oss
                v-else
                multiple
                ref="attachUpload"
                :dir="dir"
                :file-list="attachList"
                :on-complete="handleAttachComplete"
              ></upload-oss>
            </td>
          </tr>
        </tbody>
      </table>

      <div class="text-center" v-if="!isViewMode">
        <el-button class="btn-long" type="primary" @click="handlePass">登记</el-button>
        <el-button class="btn-long" type="danger" @click="handleReject">拒绝</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumRepayType } from '@/credit/plugins/enum'
import { enumGuaFundsSelfType } from '@/credit/views/county/unionProvince/components/projectApprove/index'
import { mul, add, div } from '@vimi/utils-tool'
import { attachAdapter } from '@/bank/components/attach/index'
import { deleteOss } from '@/common/api/oss'
import AttachList from '@/bank/views/business/limit/history/attach/AttachList'
import SelectOrgBank from '@/bigcredit/views/program/components/SelectOrgBank'

export default {
  components: {
    AttachList,
    SelectOrgBank,
  },
  props: {
    viewMode: { type: Boolean, default: true },
    queryId: String,
  },
  data() {
    return {
      enumGuaFundsSelfType,
      loading: false,
      viewList: [],
      attachList: [],
      attachAready: [],
      parentTag: '放款附件',
      attachTag: '放款凭证（借据）',
      params: {
        fields: [
          'months',
          'customer_name',
          'reply_funds',
          'load_end_date',
          'gua_rate',
          'load_date',
          'load_rate',
          'loan_approval_status',
          'confuse_status',
          'confuse_time',
          'confuse_des',
          'bank_type',
          'bank_code',
          'bank_name',
          'bank_id',
          'gua_type',
          'gua_fee_coll_type',
        ],
      },
      tableName: 'customer_related',
      relatedData: {},
      // 还款计划
      enumRepayType,
      editData: {
        reply_funds: '',
        months: '',
        gua_rate: '',
        load_date: '',
        load_end_date: '',
        load_rate: '',
        bank_type: '',
        bank_code: '',
        bank_name: '',
        bank_id: '',
        gua_fee_coll_type: '',
      },
      dir: 'credit/normal/register',
      // noticeData: {}
      guaFeeData: [],

      playList: [],
      repayListData: [],
      playIndex: 0,
    }
  },
  computed: {
    ...mapGetters(['org', 'user', 'entrustContract']),
    isViewMode() {
      return this.viewMode
    },
    tdClass() {
      return this.isViewMode ? '' : 'input-td'
    },
    isBankOrg() {
      return this.org.orgClass === 'org_bank'
    },
    repayYear() {
      return Math.ceil(+this.editData.months / 12)
    },
    hasContract() {
      return !!this.entrustContract.entrust_contract_id
    },
    repayFunds() {
      return mul(this.editData.reply_funds, 1e4)
    },
    repaySum() {
      return this.playList.reduce((a, b) => {
        return add(a, b.capital)
      }, 0)
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.params['customer_related_id.eq'] = this.queryId
        this.getData()
        this.getAttach()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleRowClick(index) {
      this.playIndex = index
    },
    handleRowDelete() {
      const len = this.playList.length
      if (len < 2) {
        return
      }
      const data = this.playList[this.playIndex]
      if (data.repay_funds_total > 0) {
        return this.$message.warning('还款计划已对应有还款登记不能删除')
      } else {
        this.playList.splice(this.playIndex, 1)
        if (this.playIndex >= len - 1) {
          this.playIndex--
        }
      }
    },
    handleRowAdd() {
      this.playList.push({
        capital: '',
        pay_time: '',
      })
    },
    setItemFee(v, item) {
      item.actual_warrant_fee = div(mul(v, this.editData.gua_rate), 100)
    },
    setDueDate(v, i) {
      const startDate = new Date(v)
      this.guaFeeData = this.guaFeeData.map((item, index) => {
        if (index > i) {
          item.due_warrant_date = v
            ? `${startDate.getFullYear() + index - i}-${
                startDate.getMonth() + 1
              }-${startDate.getDate()}`
            : ''
        }
        return item
      })
    },
    setGuaFee() {
      if (!+(this.editData.gua_rate || '')) {
        this.guaFeeData = []
        return
      }
      const years = Math.ceil(+(this.editData.months || '') / 12)
      if (+this.editData.gua_fee_coll_type !== 2) {
        this.guaFeeData = []
        this.guaFeeData.push({
          actual_warrant_fee: div(
            mul(+(this.editData.reply_funds || ''), +(this.editData.gua_rate || ''), years),
            100
          ),
          due_warrant_date: '',
          plan_left_funds: this.editData.reply_funds,
          customer_related_id: this.queryId,
          gua_rate: this.editData.gua_rate,
        })
        return
      }

      this.guaFeeData = []
      for (let i = 1; i <= years; i++) {
        this.guaFeeData.push({
          actual_warrant_fee: div(
            mul(+(this.editData.reply_funds || ''), +(this.editData.gua_rate || '')),
            100
          ),
          due_warrant_date: '',
          plan_left_funds: this.editData.reply_funds,
          customer_related_id: this.queryId,
          gua_rate: this.editData.gua_rate,
        })
      }
    },
    setPublicName(bank) {
      this.editData.bank_type = bank.agency_type_sub || ''
      this.editData.bank_code = bank.agency_code || ''
      this.editData.bank_name = bank.agency_name || ''
    },
    handleReject() {
      const data = {
        loan_approval_status: 4,
        confuse_status: 3,
        confuse_time: this.$utils.dateFormat(new Date()),
        confuse_person: this.user.realName,
      }
      this.$prompt('请输入拒绝说明', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入拒绝说明' : true),
      }).then(({ value }) => {
        data.confuse_des = value
        this.$api
          .updateData(this.$serviceName, 'customer_related', this.queryId, data)
          .then(() => {
            this.$message.success('已拒绝！')
            this.$emit('success', true)
            this.beforeClose()
          })
          .catch(() => this.$message.error(`提交失败，请重试！`))
      })
    },
    handleAttachComplete(files) {
      const { attachAready } = this
      const addFiles = files.filter(file => !attachAready.find(it => it.attachment === file.url))
      const deleteFiles = attachAready.filter(it => !files.find(file => file.url === it.attachment))

      const promise = []
      if (addFiles.length) {
        promise.push(
          this.$api.addBatch(
            'credit',
            'datum_customer_attachment',
            addFiles.map(it => ({
              attachment: it.url,
              attachment_type: this.attachTag,
              parent_attachment_type: this.parentTag,
              customer_related_id: this.queryId,
              file_type: 2,
              remark: it.name,
            }))
          )
        )
      }
      if (deleteFiles.length) {
        promise.push(
          this.$api.deleteData({
            table: 'datum_customer_attachment',
            id: deleteFiles.map(it => it.id).join(','),
          }),
          deleteOss(deleteFiles.map(it => it.attachment))
        )
      }
      Promise.all(promise).then(() => {
        this.getAttach()
      })
      this.registerData()
    },
    getAttach() {
      if (!this.queryId) {
        return
      }
      this.$api
        .getData({
          table: 'datum_customer_attachment',
          params: {
            'customer_related_id.eq': this.queryId,
            'attachment_type.eq': this.attachTag,
          },
        })
        .then(res => {
          this.attachAready = res?.data ?? []
          this.initAttach()
        })
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      Promise.all([
        this.$store.dispatch('getEntrustContract', this.queryId),
        this.$api.getData(this.$serviceName, this.tableName, this.params),
        this.$api.getData({
          table: 'credit_warrant_fee_record',
          params: {
            'customer_related_id.eq': this.queryId,
          },
        }),
        this.$api.getData(
          this.$serviceName,
          'datum_repay_list_view_new',
          {
            'customer_related_id.eq': this.queryId,
            fields: ['datum_repay_list_id', 'capital', 'pay_time', 'repay_funds_total'],
          },
          { pay_time: 'asc' }
        ),
      ])
        .then(([_entrust, res, fee, list]) => {
          this.relatedData = res?.data?.[0] ?? {}
          this.initContractByExist()
          this.guaFeeData = fee?.data ?? []
          if (!this.guaFeeData.length && !this.isViewMode) {
            this.setGuaFee()
          }
          const data = list?.data ?? []
          this.playList = data
          if (!data.length && !this.isViewMode) {
            this.handleRowAdd()
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    initAttach() {
      // 附件
      this.attachList = this.attachAready.map(attachAdapter)
      this.viewList = [
        {
          tag: this.attachTag,
          attachs: this.attachList,
        },
      ]
    },
    initContractByExist() {
      this.setByRelatedIfEmpty()
    },
    setByRelatedIfEmpty() {
      const fistRegist = +this.relatedData.loan_approval_status === 3
      const data = fistRegist ? this.relatedData : this.entrustContract
      Object.keys(this.editData).forEach(key => {
        this.editData[key] = data[key] || this.entrustContract[key] || this.relatedData[key]
      })
      if (!fistRegist) {
        this.editData.months = this.entrustContract.load_years || ''
      }
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    handlePass() {
      for (let i = 0; i < this.guaFeeData.length; i++) {
        if (!this.guaFeeData[i].due_warrant_date) {
          return this.$message.warning('请完善担保费信息')
        }
        this.guaFeeData[i].due_warrant_fee =
          +this.editData.gua_fee_coll_type === 1
            ? div(mul(+(this.editData.reply_funds || ''), +(this.editData.gua_rate || '')), 100)
            : this.guaFeeData[i].actual_warrant_fee
        this.guaFeeData[i].gua_rate = this.editData.gua_rate
      }
      this.editData.gua_fee = this.guaFeeData.reduce(
        (prev, curr) => add(prev, curr.actual_warrant_fee),
        0
      )

      this.repayListData = []
      for (const item of this.playList) {
        if (item.pay_time) {
          if (!+item.capital) {
            return this.$message.warning('请输入还款金额')
          }
          if (+item.capital < +item.repay_funds_total) {
            return this.$message.warning(
              `${item.pay_time}还款金额不能小于已登记还款金额${item.repay_funds_total}`
            )
          }
          const data = {
            customer_related_id: this.queryId,
            pay_time: item.pay_time,
            capital: item.capital || '',
          }
          if (item.datum_repay_list_id) {
            data.datum_repay_list_id = item.datum_repay_list_id
          }
          this.repayListData.push(data)
        } else if (item.capital) {
          return this.$message.warning('请选择还款时间')
        }
      }
      if (this.repaySum !== this.repayFunds) {
        return this.$message.error(
          `还款计划本金合计金额（${this.repaySum}元）与放款金额（${this.repayFunds}元）不相等，请先调整还款计划！`
        )
      }

      if (!this.validator()) {
        return
      }

      this.onSave()
    },
    validator() {
      const enumValid = {
        load_date: '请输入放款开始时间',
        load_end_date: '请输入放款结束时间',
        bank_id: '请选择放款银行',
      }
      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.editData[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }
      return true
    },
    onSave() {
      this.$utils
        .msgbox({
          message: `确定登记?`,
          type: 'info',
          beforeClose: () => this.$refs.attachUpload.submit(),
        })
        .then(() => {
          this.$emit('success', true)
          this.beforeClose()
        })
        .catch(() => {
          this.$message.error(`登记失败，请重试！`)
        })
    },
    registerData() {
      const data = {
        ...this.editData,
        loan_approval_status: 3,
        customer_related_id: this.queryId,
      }
      const formData = {
        masterTableInfo: JSON.stringify(data),
        masterTableName: 'customer_related',
        slaveTableInfo: JSON.stringify(this.guaFeeData.filter(item => item.due_warrant_date)),
        slaveTableName: 'credit_warrant_fee_record',
        slaveTableName1: 'datum_repay_list',
        slaveTableInfo1: JSON.stringify(this.repayListData),
      }
      return this.$api
        .relatedUpdate(this.$serviceName, formData)
        .catch(err => this.$message.error(err?.data?.error_description || '保存失败，请重试！'))
    },

    getSums(list) {
      let [capitalSum, interestSum] = [0, 0]
      for (const item of list) {
        const capital = Number.parseFloat(item.capital)
        capitalSum += isNaN(capital) ? 0 : capital

        const interest = Number.parseFloat(item.interest)
        interestSum += isNaN(interest) ? 0 : interest
      }
      return [Math.round(capitalSum * 1e2) / 1e2, Math.round(interestSum * 1e2) / 1e2]
    },
  },
}
</script>

<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
.input-td /deep/ .el-input-group__append {
  background-color: #ffe;
  border: none;
}
.input-td {
  background-color: #ffffee;
}
.tr-current {
  .input-td /deep/ {
    .el-input__inner {
      background-color: #ffffb9da;
      border: none;
    }
    .el-input-group__append {
      background-color: #ffffb9da;
      border: none;
    }
  }
}
</style>
